const Router = require('@koa/router')
const router = new Router()

const {order} = require('../vri')
const db = require('../db')

router.get('/list', async (ctx) => {
  const {user} = ctx.state
  if (!user) return ctx.error(401)
  const data = await db.find({
    form: 'order',
    field: ['id', 'createdAt'],
    virtual: ['cover'],
    where: {
      userid: user.id,
    },
  })
  if (!data) return ctx.error(431)
  ctx.body = {
    code: 200,
    data,
  }
})

router.get('/fromid', async (ctx) => {
  const {user} = ctx.state
  if (!user) return ctx.error(401)
  const {query} = ctx
  const {adopt, error, value} = order.fromid.verifies(query)
  if (!adopt) return ctx.error(430, {error: error.toString()})
  const {id} = value
  const data = await db.first({
    form: 'order',
    virtual: ['shoppingCarts'],
    where: {
      userid: user.id,
      id,
    },
  })
  if (!data) return ctx.error(431)
  ctx.body = {
    code: 200,
    data,
  }
})

router.post('/settlement', async (ctx) => {
  const {user} = ctx.state
  if (!user) return ctx.error(401)
  const {body} = ctx.request
  const {adopt, error, value} = order.fromid.verifies(body)
  if (!adopt) return ctx.error(430, {error: error.toString()})
  const {id} = value
  const data = await db.first({
    form: 'order',
    field: ['scid', 'price'],
    where: {
      id,
    },
  })
  if (!data) return ctx.error(431)
  await db.update({
    form: 'shopping-cart',
    where: {
      userid: user.id,
      settle: 1,
      id: data.scid,
    },
    set: {
      settle: 2,
    },
  })
  await db.delete({
    form: 'order',
    where: {
      id,
    },
  })
  ctx.body = {
    code: 200,
    id: data.scid,
    price: data.price
  }
})

module.exports = router.routes()
